﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using yzrilyzr.util;

namespace FAQ_UI.window
{
	public partial class SafeForm : Form
	{
		private delegate int HookHandle(int nCode, int wParam, IntPtr lParam);

		[StructLayout(LayoutKind.Sequential)]
		public class HookStruct
		{
			public int vkCode;
			public int scanCode;
			public int flags;
			public int time;
			public int dwExtraInfo;
		}

		private int _hHookValue;

		public SafeForm()
		{
			InitializeComponent();
			SetWindowDisplayAffinity(Handle, 1);
			_hHookValue = SetWindowsHookEx(13, new HookHandle(OnHookProc), Handle, GetCurrentThreadId());
			Console.WriteLine(FAQUtil.CheckVM());
			Console.WriteLine(FAQUtil.isScreenProcessRunning());
			Console.WriteLine(FAQUtil.isScreenServiceRunning());
		}

		[DllImport("kernel32.dll")]
		private static extern int GetCurrentThreadId();

		[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint dwAffinity);

		[DllImport("Kernel32.dll")]
		public static extern uint GetLastError();

		[DllImport("user32.dll")]
		private static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);

		[DllImport("user32.dll")]
		private static extern int SetWindowsHookEx(int idHook, HookHandle lpfn, IntPtr hInstance, int threadId);

		private Flag screenshot = new Flag();
		private DT screenshotDt = new DT();

		private int OnHookProc(int nCode, int wParam, IntPtr lParam)
		{
			if (nCode >= 0)
			{
				//转换结构
				HookStruct hookStruct = (HookStruct)Marshal.PtrToStructure(lParam, typeof(HookStruct));
				bool handle = false;
				//调用客户提供的事件处理程序。
				ProcessKeyHandle(hookStruct, out handle);
				if (handle) return 1; //1:表示拦截键盘,return 退出
			}
			return CallNextHookEx(_hHookValue, nCode, wParam, lParam);
		}

		private void ProcessKeyHandle(HookStruct hookStruct, out bool handle)
		{
			handle = false;
			if (hookStruct.vkCode == (int)Keys.S && (int)Control.ModifierKeys == (int)Keys.Shift)
			{
				handle = true;
				Hide();
			}
			if (hookStruct.vkCode == (int)Keys.PrintScreen)
			{
				handle = true;
				Hide();
			}
			/*int[] f = { 641, 642, 13, 14, 6, 7, 8, 512, 132, 32, 61, 160, 675, 134, 28, 70, 71 };
			foreach (var i in f) if (msg == i) return IntPtr.Zero;
			//Console.WriteLine(msg);

			if (msg != 257) return IntPtr.Zero;
			//Console.WriteLine(msg);
			//Console.WriteLine(wParam);
			int kc = wParam.ToInt32();
			if (kc == 91) screenshot.add(1);
			if (kc == 16) screenshot.add(0b10);
			if (kc == 83) screenshot.add(0b100);
			if (screenshot.has(0b111) && screenshotDt.getMs() < 5000)
			{
				Console.WriteLine("Screenshot");
			}
			if (wParam.ToInt64() == 0x2c)
			{
				Console.WriteLine("Screenshot");
				Hide();
			}
			return IntPtr.Zero;*/
		}
	}
}